#!/usr/bin/env python3
# # -*- coding: utf-8 -*-

from venv import logger
from persistent.mapping import PersistentMapping
from web_server.models.db_client import DBClient
from web_server.device_proxy import DeviceProxy
from web_server.models.project import Project

class ProjectMgr:
    def __init__(self, device_proxy: DeviceProxy, db_client: DBClient):
        self.device_proxy = device_proxy
        self.db_client = db_client
        if not hasattr(self.db_client.root, 'projects'):
            self.db_client.root.projects = PersistentMapping()
            self.db_client.flush()
        self.projects = self.db_client.root.projects

    def __del__(self):
        self.destroy()

    def destroy(self):
        self.db_client = None
        self.device_proxy = None

    def get_project(self, key: str) -> Project:
        """获取项目"""
        return self.projects.get(key)

    def new_project(
        self,
        owner: str,
        name: str,
        type: str,
        board: str,
        product: str,
        platform: str,
        version: str,
        description: str):
        key = f'{owner}/{name}'
        if self.projects.get(key) is not None:
            logger.info(f'项目 {key} 已存在')
            return None
        project = Project(
            owner=owner,
            name=name,
            type=type,
            board=board,
            product=product,
            platform=platform,
            version=version,
            description=description)
        self.projects[key] = project
        return project

    def delete_project(self, key: str):
        """删除项目"""
        if self.projects.get(key) is None:
            logger.info(f'项目 {key} 不存在')
            return None
        self.projects.pop(key)